package com.gxa.controller;

import com.gxa.common.R;
import com.gxa.pojo.FileUser;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * User: admin
 */
@Controller
public class UploadFileUserController {

    @RequestMapping(value = "/ajax_upload",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public R updateFile(FileUser fileUser, HttpServletRequest request) throws IOException {
        R r = new R();
        System.out.println(fileUser.getUsername());
        System.out.println(fileUser.getPassword());
        if(fileUser.getUser_pic().isEmpty()){
            r.setCode(500);
            r.setMsg("没有选中文件");
        }else{//正常上传
            String uploadPath = request.getServletContext().getRealPath("") + File.separator + "upload" + File.separator;
            File file = new File(uploadPath);
            if(!file.exists()){
                file.mkdirs();
            }
            MultipartFile multipartFile = fileUser.getUser_pic();
            String fileName = multipartFile.getOriginalFilename();
            File newFile = new File(uploadPath + fileName);
            System.out.println("newFile=" + newFile);
            //上传
            FileCopyUtils.copy(multipartFile.getBytes(),newFile);
        }
        //调用Service
        r.setCode(200);
        r.setMsg("成功");
        return r;
    }
}
